/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.jwt.security.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.star.framework.jwt.security.entity.Token;
import cn.star.framework.jwt.security.repository.TokenRepository;
import cn.star.framework.jwt.security.service.TokenService;
import cn.star.framework.service.AbstractService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Service
public class TokenServiceImpl extends AbstractService<Token, String, TokenRepository>
    implements TokenService {

  public TokenServiceImpl(TokenRepository repository) {
    super(repository);
  }

  @Override
  public void validate(Token token) {
    Assert.isFalse(
        token == null || StrUtil.isBlank(token.getAccessToken()),
        "Token value empty, validate failure");

    Token ot = repository.findByAccessTokenEquals(token.getAccessToken());

    Assert.isFalse(
        ot == null || StrUtil.isBlank(ot.getAccessToken()),
        "Assess token absent, Token value may be tampered with, validate failure");

    String ip = token.getClientIp();
    if (StrUtil.isNotBlank(ip)) {
      Assert.isFalse(
          !ip.equals(ot.getClientIp()),
          "The new client uses the original Token, validate failure, ✓ {}, ✗ {}",
          ot.getClientIp(),
          ip);
    }

  }

  /**
   * 不使用事务注解出错<br>
   *
   * <pre>
   * No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call; nested exception is javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
   * 	at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:403) ~[spring-orm-5.3.30.jar:5.3.30]
   * 	at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:235) ~[spring-orm-5.3.30.jar:5.3.30]
   * 	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551) ~[spring-orm-5.3.30.jar:5.3.30]
   * </pre>
   *
   * @param accessToken
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteByAccessToken(String accessToken) {
    repository.deleteByAccessTokenEqualsOrPrimitiveTokenEquals(accessToken, accessToken);
  }

  @Override
  public Token findByAccessToken(String accessToken) {
    return repository.findByAccessTokenEquals(accessToken);
  }
}
